#include<iostream>
#include<algorithm>
#include<vector>
class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> ret;
        int n = nums.size();
        sort(nums.begin(), nums.end());
        for (int i = 0; i < n - 3;) {
            for (int j = i + 1; j < n - 2;) {
                long long tar = (long long)target - nums[i] - nums[j];
                int left = j + 1, right = n - 1;
                while (left < right) {
                    int sum = nums[left] + nums[right];
                    if (tar < sum) {
                        --right;
                    }
                    else if (tar > sum) {
                        ++left;
                    }
                    else {
                        ret.push_back({ nums[i],nums[j],nums[left],nums[right] });
                        ++left;
                        --right;
                        while (nums[left] == nums[left - 1] && left < right) ++left;
                        while (nums[right] == nums[right + 1] && left < right) --right;
                    }
                }
                ++j;
                while (j < n - 2 && nums[j] == nums[j - 1]) ++j;
            }
            ++i;
            while (i < n - 3 && nums[i] == nums[i - 1]) ++i;
        }
        return ret;
    }
};